//接口鉴权
import axios from './axios'
import Cache from './cache'
const AuthRequest = (req, method = 'GET', url = '', data = {}) => {
    if(process.server){
        let origin = getIp(req)
        let path = encodeURI(req.originalUrl)
        //服务端
        return axios.get('com/auth?path=' + path+'&origin='+origin).then(res => {
            console.log(res)
            if (res.code != 200) {
                
                return Promise.reject(res);
            } else {
                
                return axiosRequest(res.data, method, url, data)
            }
        })
    }else{
        //客户端
        const Authorization = Cache.get('Authorization')
        if(Authorization){
            return axiosRequest(Authorization, method, url, data)
        }else{
            window.location.reload()
            return Promise.reject({
                code:406,
                msg:'请尝试刷新！！！'
            });
        }
        
    }
}

const axiosRequest = (Authorization, method = 'GET', url = '', data = {}) => {
    const conf = {
        url,
        method,
        headers: {
            Authorization,
        }
    }
    if (method == 'GET') {
        conf['params'] = data
    } else {
        conf['data'] = data
    }
    
    return axios.request(conf)
}
const getIp = function (req) {
    let CLIENT_REQUEST_IP = "";
    if (req.headers['x-forwarded-for'] && req.headers['x-forwarded-for'] != 'unknown') {
        CLIENT_REQUEST_IP = req.headers['x-forwarded-for'].split(",")[0];
        return CLIENT_REQUEST_IP
    }
    if (req.headers['Proxy-Client-IP'] && req.headers['Proxy-Client-IP'] != 'unknown') {
        CLIENT_REQUEST_IP = req.headers['Proxy-Client-IP'].split(",")[0];
        return CLIENT_REQUEST_IP
    }
    if (req.headers['WL-Proxy-Client-IP'] && req.headers['WL-Proxy-Client-IP'] != 'unknown') {
        CLIENT_REQUEST_IP = req.headers['WL-Proxy-Client-IP'].split(",")[0];
        return CLIENT_REQUEST_IP
    }
    if (req.headers['HTTP_CLIENT_IP'] && req.headers['HTTP_CLIENT_IP'] != 'unknown') {
        CLIENT_REQUEST_IP = req.headers['HTTP_CLIENT_IP'].split(",")[0];
        return CLIENT_REQUEST_IP
    }
    if (req.headers['HTTP_X_FORWARDED_FOR'] && req.headers['HTTP_X_FORWARDED_FOR'] != 'unknown') {
        CLIENT_REQUEST_IP = req.headers['HTTP_X_FORWARDED_FOR'].split(",")[0];
        return CLIENT_REQUEST_IP
    }
    if (req.connection.remoteAddress && req.connection.remoteAddress != 'unknown') {
        CLIENT_REQUEST_IP = req.connection.remoteAddress.split(",")[0];
        return CLIENT_REQUEST_IP
    };
}
export {
    AuthRequest,
}